package com.idanchuang.component.consumer;

import com.idanchuang.component.consumer.config.RpcConfig;
import com.idanchuang.component.consumer.helper.ConfigConsumerRestTemplate;
import com.idanchuang.component.consumer.servlet.ConsumerServletRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Configuration
@ConditionalOnClass(RestTemplate.class)
public class ConsumerRestTemplateAutoConfiguration {

    @Autowired(required = false)
    private ConsumerServletRequestContext consumerServletRequestContext;

    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder().build();
    }

    @Bean
    @ConditionalOnMissingBean(ConfigConsumerRestTemplate.class)
    public ConfigConsumerRestTemplate configConsumerRestTemplate(List<RestTemplate> restTemplates, RpcConfig rpcConfig) {
        RestTemplateInterceptor interceptor = new RestTemplateInterceptor(rpcConfig, consumerServletRequestContext);
        restTemplates.forEach(r -> r.getInterceptors().add(interceptor));
        return new ConfigConsumerRestTemplate();
    }

}
